package com.ruoyi.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Friend;
import com.ruoyi.system.service.IFriendService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 用户好友Controller
 * 
 * @author ruoyi
 * @date 2025-01-06
 */
@RestController
@RequestMapping("/system/friend")
public class FriendController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(FriendController.class);

    @Autowired
    private IFriendService friendService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询用户好友列表
     */
//    @PreAuthorize("@ss.hasPermi('system:friend:list')")
    @GetMapping("/list")
    public TableDataInfo list(Friend friend)
    {
        startPage();
        // 移除默认status设置，显示所有状态
        // if (friend.getStatus() == null) {
        //     friend.setStatus("1");
        // }
        List<Friend> list = friendService.selectFriendList(friend);
        return getDataTable(list);
    }

    /**
     * 导出用户好友列表
     */
//    @PreAuthorize("@ss.hasPermi('system:friend:export')")
    @Log(title = "用户好友", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Friend friend)
    {
        List<Friend> list = friendService.selectFriendList(friend);
        ExcelUtil<Friend> util = new ExcelUtil<Friend>(Friend.class);
        util.exportExcel(response, list, "用户好友数据");
    }

    /**
     * 获取用户好友详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:friend:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(friendService.selectFriendById(id));
    }

    /**
     * 新增用户好友
     */
//    @PreAuthorize("@ss.hasPermi('system:friend:add')")
    @Log(title = "用户好友", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Friend friend)
    {
        // 检查好友关系是否已存在
        int count = friendService.checkFriendExists(friend.getUserId(), friend.getFriendId());
        if (count > 0) {
            return error("该好友关系已存在，无法重复添加");
        }
        
        // 设置初始状态
        friend.setStatus("0");  // 待确认状态
        friend.setIsDeleted("0");
        
        return toAjax(friendService.insertFriend(friend));
    }

    /**
     * 修改用户好友
     */
//    @PreAuthorize("@ss.hasPermi('system:friend:edit')")
    @Log(title = "用户好友", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Friend friend)
    {
        return toAjax(friendService.updateFriend(friend));
    }

    /**
     * 删除用户好友
     */
//    @PreAuthorize("@ss.hasPermi('system:friend:remove')")
    @Log(title = "用户好友", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(friendService.deleteFriendByIds(ids));
    }

    /**
     * 获取用户的好友列表
     */
    @GetMapping("/user/{userId}")
    public AjaxResult getUserFriends(@PathVariable("userId") Long userId)
    {
        List<Friend> list = friendService.selectFriendsByUserId(userId);
        return success(list);
    }

    /**
     * 搜索用户
     */
    @GetMapping("/search")
    public AjaxResult searchUsers(String userName) {
        if (StringUtils.isEmpty(userName)) {
            return error("用户名不能为空");
        }
        
        try {
            // 创建查询条件
            SysUser user = new SysUser();
            user.setUserName(userName);
            user.setNickName(userName);
            
            // 设置其他查询条件
            user.setStatus("0");  // 只查询正常状态的用户
            user.setDelFlag("0"); // 未删除的用户
            
            // 排除当前登录用户
            Long currentUserId = SecurityUtils.getUserId();
            
            log.info("搜索条件: userName={}, currentUserId={}", userName, currentUserId);
            List<SysUser> users = userService.searchUsers(userName, currentUserId);
            log.info("搜索结果: {}", users);
            
            return success(users);
        } catch (Exception e) {
            log.error("搜索用户失败", e);
            return error("搜索用户失败：" + e.getMessage());
        }
    }
}
